(function (exports) {
    var $ = null;
    var EmailLayer = cc.Layer.extend({
        EmailData: [],
        addListener: function (code, listener) {
            network.addListener(code, listener, this);
        },
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);

            var that = this;
            this.refreshEmailList(); //刷新邮箱列表
            this.addListener(1024, function (data) {
                var mailsdata = data.mailsdata;
                that.EmailData = mailsdata;
                that.initEmailUI();
            },that);
            this.addListener(1026, function (data) {
                that.refreshEmailList();
            },that);
            this.addListener(1028, function (data) {
                if (data.deltype == 0) { //一键删除
                    that.refreshEmailList();
                    that._$('pannelBg.content').setVisible(false);
                }
            },that);
            this.addListener(1030, function (data) {
                showAlert("领取成功!");
                that.refreshEmailList();
                network.send(3013); //核对金币 钻石 房卡 （礼券在打开礼券商城会有请求）
            },that);

            that._$('pannelBg.content').setVisible(false);
        },
        refreshEmailList: function () {
            var data = {
                userid: gameData.uid + "",
                gameid: app.area + "",
                showtype: 0,
                info: [{type: 'version', valtype: 1, sval: '1'}],
            };
            network.sendProto(1023, data);
        },
        onExit: function () {
            cc.Layer.prototype.onExit.call(this);
            network.removeListenersForTarget(this);
        },
        ctor: function () {
            this._super();
            var that = this;

            var scene = loadNodeCCS(res.EmailLayer_json, this);
            $ = create$(this.getChildByName('Layer'));
            this._$ = $;

            this._$('pannelBg.txtEmpty').setVisible(false);

            // var size = $('pannelBg.bg').getContentSize();
            // var piaodai = getCreateRoomAni(7);
            // piaodai.setPosition(size.width/2, size.height - 50);
            // $('pannelBg.bg').addChild(piaodai);

            TouchUtil.setOnclickListener(this._$('pannelBg.btn_close'), function (node) {
                that.parent.removeFromParent(true);
            });
            //删除已读
            TouchUtil.setOnclickListener(this._$('pannelBg.btnDel'), function (node) {
                if (that.EmailData.length == 0) {
                    showAlert("暂无邮件信息！");
                } else {
                    var data = {
                        userid: gameData.uid + "",
                        gameid: app.area + "",
                        mailid: [],
                        deltype: 0, //0：一键删除非未领邮件 1：单封删除
                    };
                    network.sendProto(1027, data);
                }
            });
            //一键已读
            TouchUtil.setOnclickListener(this._$('pannelBg.btnReadAll'), function (node) {
                if (that.EmailData.length == 0) {
                    showAlert("暂无邮件信息!");
                } else {
                    var data = {
                        userid: gameData.uid + "",
                        gameid: app.area + "",
                        mailid: [],
                        readtype: 0,
                    };
                    network.sendProto(1025, data);
                }
            });
            //全部领取
            TouchUtil.setOnclickListener(this._$('pannelBg.btnGetAll'), function (node) {
                if (that.EmailData.length == 0) {
                    showAlert("暂无邮件信息!");
                } else {
                    var mailIdT = [];
                    for (var i = 0; i < that.EmailData.length; i++) {
                        var emailData = that.EmailData[i];
                        if (emailData.get == 1) { //0 无附件 1 有附件 2附件已领取
                            mailIdT.push(emailData.mailid);
                        }
                    }
                    var data = {
                        userid: gameData.uid + "",
                        gameid: app.area + "",
                        mailid: mailIdT,
                    };
                    network.sendProto(1029, data);
                }
            });
        },
        initEmailUI: function () {
            var that = this;
            var count = 0;

            var arr = [];
            for (var i = 0; i < that.EmailData.length; i++) {
                var createTime = that.EmailData[i].createtime;
                var nowTime = Math.floor(new Date().getTime() / 1000);
                var disTime = nowTime - createTime;
                var tenDaySec = 60 * 60 * 24 * 10; //10天的秒数
                if (disTime < tenDaySec) {
                    arr.push(that.EmailData[i]);
                }
                if (that.EmailData[i].read == 1 && disTime < tenDaySec) {
                    count++;
                }
            }
            that.EmailData = arr;
            that._$('pannelBg.emailNum').setString(count + '/' + that.EmailData.length + ' 邮件最多保留10天');
            that._$('pannelBg.txtEmpty').setVisible(that.EmailData.length == 0);

            if (that.tableview) {
                tableViewRefresh(that.tableview); //刷新一遍 用于查询
            } else {
                var tableviewLayer = that._$('pannelBg.tableview');
                var tableview = new cc.TableView(that, cc.size(tableviewLayer.getContentSize().width, tableviewLayer.getContentSize().height));
                tableview.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
                tableview.setVerticalFillOrder(cc.TABLEVIEW_FILL_BOTTOMUP);
                tableview.x = 0;
                tableview.y = 0;
                tableview.setDelegate(that);
                tableview.setBounceable(true);
                tableviewLayer.addChild(tableview);
                that.tableview = tableview;
            }
        },
        setContentLayer: function(emailData){
            this._$('pannelBg.content').setVisible(true);
            this._$('pannelBg.content.txt_title').setString(emailData.subject);
            this._$('pannelBg.content.txt_content').setString(emailData.content);

            var attachments = emailData.attachments;
            if(attachments){
                this._$('pannelBg.content.scrollview').setVisible(true);
                var scrollWidth = 600;
                if(100*attachments.length >= 600)  scrollWidth = 100*attachments.length;
                this._$('pannelBg.content.scrollview').setInnerContainerSize(cc.size(scrollWidth, 150));
                this._$('pannelBg.content.scrollview').removeAllChildren();
                for(var i=0;i<attachments.length;i++){
                    var imgItem = null;
                    if(!this._$('pannelBg.content.scrollview.imgItem' + i)){
                        imgItem = duplicateNode(this._$('pannelBg.imgItem0'));
                        imgItem.setName("imgItem" + i);
                        this._$('pannelBg.content.scrollview').addChild(imgItem);
                        imgItem.setPosition(cc.p(70 + 120*i, 80));
                        var moneyMap = {
                            coin: 'item_coin',
                            roomcard: 'item_card',
                            diamond: 'item_diamond'
                        };

                        var itemid = attachments[i].itemid;
                        if (moneyMap[itemid]) { //货币从本地获取
                            var sp = new cc.Sprite(this._$(moneyMap[itemid]).getTexture());
                            // sp.setScale(0.5);
                            $('item', imgItem).addChild(sp, 10);
                        }else {
                            var itemInfo = ItemData.getItemInfoByCode(attachments[i].itemid);
                            if(itemInfo) {
                                var imageUrl = itemInfo.ImgSml || itemInfo.ImgBig;
                                downLoadImage(imageUrl, function (texture) {
                                    $('item', imgItem).removeAllChildren();
                                    var sp = new cc.Sprite(texture);
                                    // sp.setScale(0.5);
                                    $('item', imgItem).addChild(sp, 10);
                                });
                            }
                        }


                        $('num', imgItem).setString(equalNum(attachments[i].itemvalue));
                        $('hadLing', imgItem).setVisible(emailData.get == 2);
                    }
                }
            }else{
                this._$('pannelBg.content.scrollview').setVisible(false);
            }

        },

        //点击cell
        tableCellTouched: function (table, cell) {
            var that = this;
            var idx = cell.getIdx();
            var emailData = that.EmailData[idx];
            if (emailData.read == 0) {
                var data = {
                    userid: gameData.uid + "",
                    gameid: app.area + "",
                    mailid: [emailData.mailid],
                    readtype: 1,
                };
                network.sendProto(1025, data);
            }
            cell.getChildByName('cellrow').getChildByName('imgOpen').setVisible(true);
            cell.getChildByName('cellrow').getChildByName('imgunread').setVisible(false);

            // that.addChild(new EmailShowContent(emailData));
            that.setContentLayer(emailData);
        },
        tableCellSizeForIndex: function (table, idx) {
            return cc.size(300, 100);
        },
        tableCellAtIndex: function (table, idx) {
            var that = this;
            var cell = table.dequeueCell();
            if (cell == null) {
                cell = new cc.TableViewCell();
                // var row0 = ccs.load(res.EmailItem_json, 'res/').node;
                var row0 = loadNodeCCSItem(res.EmailItem_json);
                row0.setName('cellrow');
                cell.addChild(row0);
            }
            var Layer = cell.getChildByName('cellrow');
            var data = that.EmailData[idx];
            if (data) {
                that._$('imgOpen', Layer).setVisible(data.read == 1);
                that._$('imgunread', Layer).setVisible(data.read == 0);
                that._$('txtTitle', Layer).setString(data.subject);
                var time = timestamp2time(data.createtime);
                that._$('txtDate', Layer).setString(time);
            }
            return cell;
        },
        numberOfCellsInTableView: function (table) {
            return this.EmailData.length;
        },

    });
    exports.EmailLayer = EmailLayer;

})(window);